package com.ihr360.authority.sharing.entityhandler;

import com.ihr360.authority.sharing.annonation.BizModel;
import com.ihr360.authority.sharing.dao.AuthUserResourceRepository;
import com.ihr360.authority.sharing.model.IResourceControl;
import com.ihr360.authority.sharing.model.dto.AuthUserResource;
import com.ihr360.authority.sharing.service.AuthUserResourceService;
import com.ihr360.commons.context.session.Ihr360Session;
import com.ihr360.commons.context.session.Ihr360SessionContextHolder;
import com.ihr360.commons.entity.AuthUserInfo;
import com.ihr360.commons.exception.Ihr360Exception;
import com.ihr360.commons.model.type.AccessPrivilege;
import com.ihr360.commons.model.type.ResourcePublicity;
import com.ihr360.context.SpringContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.util.StringUtils;

import javax.persistence.PostPersist;
import javax.persistence.PreRemove;

public class UserResourceHandler {
    private final static String ID = "id";
    final Logger logger = LoggerFactory.getLogger(getClass().getName());

    private AuthUserResourceRepository authUserResourceRepository;

    private AuthUserResourceService authUserResourceService;

    private int publicity;

    @PostPersist
    void onPostPersist(Object o) {
        if (o == null) {
            return;
        }
        if (authUserResourceRepository == null) {
            authUserResourceRepository = SpringContext.getBean(AuthUserResourceRepository.class);
        }

        GetBizModelName getBizModelName = new GetBizModelName(o).invoke();
        String bizModelName = getBizModelName.getBizModelName();
        BeanWrapper beanWrapper = getBizModelName.getBeanWrapper();

        Ihr360Session session = Ihr360SessionContextHolder.getSession();
        if (session != null) {
            AuthUserInfo userInfo = session.getUserInfo();
            if (userInfo != null) {
                String companyId = userInfo.getCompanyId();
                String userId = userInfo.getUserId();
                String userName = userInfo.getUserName();
                if (!StringUtils.isEmpty(companyId) && userId != null) {
                    Object idValue = beanWrapper.getPropertyValue(ID);
                    if (idValue == null) {
                        throw new Ihr360Exception(null, "无法获取id标志");
                    }
                    AuthUserResource resource = new AuthUserResource();
                    resource.setCompanyId(companyId);
                    resource.setBizModel(bizModelName);
                    resource.setUserId(userId);
                    resource.setUserAccount(userName);
                    resource.setPrivilege(AccessPrivilege.Privilege.OWNER);
                    if (IResourceControl.class.isAssignableFrom(o.getClass())) {
                        resource.setPublicity(ResourcePublicity.Publicity.PERSONAL);
                    }
                    String strId = toStringId(idValue);
                    resource.setResourceId(strId);
                    try {
                        authUserResourceRepository.save(resource);
                    } catch (Exception e) {
                        e.printStackTrace();
                        logger.error(e.getMessage(), e);
                        throw new Ihr360Exception(null, "权限设定保存失败", e);
                    }
                }
            }
        } else {
            throw new Ihr360Exception(null, "无法获取会话信息");
        }
    }

    @PreRemove
    void onPreDelete(Object o) {
        if (o == null) {
            return;
        }
        if (authUserResourceRepository == null) {
            authUserResourceRepository = SpringContext.getBean(AuthUserResourceRepository.class);
        }
        GetBizModelName getBizModelName = new GetBizModelName(o).invoke();
        String bizModelName = getBizModelName.getBizModelName();
        BeanWrapper beanWrapper = getBizModelName.getBeanWrapper();

        Ihr360Session session = Ihr360SessionContextHolder.getSession();
        if (session != null) {
            AuthUserInfo userInfo = session.getUserInfo();
            if (userInfo != null) {
                String companyId = userInfo.getCompanyId();
                String userId = userInfo.getUserId();
                if (!StringUtils.isEmpty(companyId) && userId != null) {
                    Object idValue = beanWrapper.getPropertyValue(ID);
                    if (idValue == null) {
                        throw new Ihr360Exception(null, "无法获取id标志");
                    }
                    String resourceId = toStringId(idValue);

                    try {
                        authUserResourceRepository.deleteByCompanyIdAndBizModelAndResourceId(companyId, bizModelName, resourceId);
                    } catch (Exception e) {
                        e.printStackTrace();
                        logger.error(e.getMessage(), e);
                        throw new Ihr360Exception(null, "删除权限数据失败", e);
                    }
                }
            }
        } else {
            throw new Ihr360Exception(null, "无法获取会话信息");
        }
    }

    private String toStringId(Object idValue) {
        String strId = null;
        if (idValue instanceof String) {
            strId = (String) idValue;
        } else if (idValue instanceof Long) {
            strId = String.valueOf(idValue);
        } else if (idValue instanceof Integer) {
            strId = String.valueOf(idValue);
        } else {
            strId = idValue.toString();
        }
        return strId;
    }

    private class GetBizModelName {
        private Object o;
        private BeanWrapper beanWrapper;
        private String bizModelName;

        public GetBizModelName(Object o) {
            this.o = o;
        }

        public BeanWrapper getBeanWrapper() {
            return beanWrapper;
        }

        public String getBizModelName() {
            return bizModelName;
        }

        public GetBizModelName invoke() {
            beanWrapper = new BeanWrapperImpl(o);
            BizModel bizModel = beanWrapper.getWrappedClass().getAnnotation(BizModel.class);
            bizModelName = null;
            if (bizModel != null && com.ihr360.commons.lang.StringUtils.isNotBlank(bizModel.name())) {
                bizModelName = bizModel.name();
            } else {
                bizModelName = beanWrapper.getWrappedClass().getSimpleName();
            }
            if (bizModelName == null) {
                throw new Ihr360Exception(null, "无法获取有效的模块名称");
            }
            return this;
        }
    }
}